{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "    此代码完成的是python实现归并排序结果\n",
    "    author: fuhongyu\n",
    "    time: 2018-07-27\n",
    "    时间复杂度： O(n^2)\n",
    "    目标：15分钟内完成\n",
    "    说明：归并算法,归即递归，并即合并。该算法运行速度很快，\n",
    "    但因为是递归算法，故对CPU消耗很大\n",
    "''' \n",
    "def merge(a ,b):#  合并两个list\n",
    "    i = 0\n",
    "    j = 0\n",
    "    result = []\n",
    "    while i<len(a) and j <len(b):\n",
    "        if a[i] < b[j]:\n",
    "            result.append(a[i])\n",
    "            i += 1\n",
    "        else:\n",
    "            result.append(b[j])\n",
    "            j += 1\n",
    "    if i == len(a):\n",
    "        for i in b[j:]:\n",
    "            result.append(i)\n",
    "    else:\n",
    "        for i in a[i:]:\n",
    "            result.append(i)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "def merge_sort(lists):# 对list进行排序的总函数\n",
    "    if len(lists) <= 1:\n",
    "        return lists\n",
    "    middle = len(lists)//2\n",
    "    left = merge_sort(lists[:middle])\n",
    "    right = merge_sort(lists[middle:])\n",
    "    return merge(left, right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 1, 2, 3, 3, 3, 4, 4, 4, 6, 8, 20, 34, 56]"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 测试代码\n",
    "lists = [3,4,2,6,4,8,3,0,20,34,1,4,56,3]\n",
    "merge_sort(lists)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
